package com.itheima.datasource;

import com.itheima.utils.JdbcUtils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;
//1.编写类实现DataSource接口
public class MyDataSource implements DataSource {
    //2.创建一个容器，储存链接对象
    private static CopyOnWriteArrayList<Connection> list = new CopyOnWriteArrayList<>();
    //3.初始化链接
    static {
        try {
            for (int i = 0; i < 2; i++) {
                Connection connection = JdbcUtils.getConnection();
                list.add(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    //4.编写获取链接功能
    public Connection getConnection() throws SQLException {
        Connection connection = list.remove(new Random().nextInt(list.size()));
        Connection conn = (Connection) Proxy.newProxyInstance(connection.getClass().getClassLoader(), new Class[]{Connection.class,}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("close")) {


                    list.add(connection);
                    return null;
                }else {
                    return method.invoke(connection,args);
                }
            }
        });
        return conn;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
